import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Upload, message } from 'antd';
import { fetchOSSTooken } from '@/services/commen';

interface UploadOSSProps {
  accept: string;
  listType: string;
  maxCount: number;
  showUploadList: boolean;
  isModalVisible?:boolean;
  onSetFilesURL: (value: string) => void;
}

const UploadOSS: React.FC<UploadOSSProps> = (props) => {
  const [OSSData, setOSSData] = useState<any>({});
  const [fileList, setFileList] = useState<any[]>([]);
  const {
    accept,
    children,
    listType,
    maxCount,
    showUploadList,
    onSetFilesURL,
    isModalVisible
  } = props;

  useEffect(() => {
    setFileList([])
  }, [isModalVisible])

  const init = useCallback(async () => {
    try {
      const data = await fetchOSSTooken();
      setOSSData(data);
    } catch (error: any) {
      message.error(error);
    }
  }, []);

  useEffect(() => {
    init();
    return ()=>{
      setOSSData({});
    }
  }, []);

  const handleChange = useCallback(
    ({ fileList }: any) => {
      setFileList(fileList);
      if (fileList[0]?.status === 'done') {
        message.success('上传成功');
        const value = fileList[0].url;
        onSetFilesURL(value);
      }
    },
    [onSetFilesURL],
  );

  const getExtraData = useCallback(
    (file: any) => {
      return {
        key: file.key,
        OSSAccessKeyId: OSSData.accessid,
        policy: OSSData.policy,
        Signature: OSSData.signature,
      };
    },
    [OSSData],
  );

  const handlebeforeUpload = useCallback(
    async (file: any) => {
      const expire = OSSData.expire * 1000;

      if (expire < Date.now()) {
        init();
      }

      const dir = 'ayao/';
      const suffix = file.name.slice(file.name.lastIndexOf('.'));
      const filename = Date.now() + suffix;
      file.key = dir + OSSData.dir + filename;
      file.url = OSSData.host + OSSData.dir + dir + filename;

      return file;
    },
    [OSSData, init, Date],
  );

  const Uploadprops:any = useMemo(
    () => ({
      name: 'file',
      accept: accept,
      fileList,
      action: OSSData.host,
      listType: listType,
      maxCount: maxCount,
      showUploadList: showUploadList,
      onChange: handleChange,
      data: getExtraData,
      beforeUpload: handlebeforeUpload,
    }),
    [OSSData, handleChange, getExtraData, handlebeforeUpload, props, fileList],
  );
  return <Upload {...Uploadprops}>{children}</Upload>;
};

export default UploadOSS;
